using SharpGraphT.Sharp.System.Collections.Generic;

namespace SharpGraphT.Graph; 

public class WeightedIntrusiveEdgesSpecifics<TV, TE> :
    BaseIntrusiveEdgesSpecifics<TV, TE, IntrusiveWeightedEdge>,
    IIntrusiveEdgesSpecifics<TV, TE> {


    public WeightedIntrusiveEdgesSpecifics(
        IDictionary<TE, IntrusiveWeightedEdge> edgeMap) : base(edgeMap) { }

    public override bool Add(TE e, TV sourceVertex, TV targetVertex) {
        if (e is IntrusiveWeightedEdge iwe) {
            return AddIntrusiveEdge(e, sourceVertex, targetVertex, iwe);
        }

        var previousSize = edgeMap.Count;
        var intrusiveEdge =
            edgeMap.ComputeIfAbsent(e, i => new IntrusiveWeightedEdge());
        if (previousSize >= edgeMap.Count) {
            return false;
        }

        intrusiveEdge.source = sourceVertex;
        intrusiveEdge.target = targetVertex;
        return true;
    }

    public override double GetEdgeWeight(TE e) {
        var ie = GetIntrusiveEdge(e);
        if (ie == null) {
            throw new ArgumentException($"no such edge in graph: {e}");
        }

        return ie.Weight;
    }

    public override void SetEdgeWeight(TE e, double weight) {
        var ie = GetIntrusiveEdge(e);
        if (ie == null) {
            throw new ArgumentException($"no such edge in graph: {e}");
        }

        ie.Weight = weight;
    }

    protected override IntrusiveWeightedEdge GetIntrusiveEdge(TE e) =>
        e is IntrusiveWeightedEdge iew ? iew : edgeMap[e];
}